package com.lac.component.cas;

/**
 * @author xiaokuixiao
 * date2025/7/9 13:49
 */
import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStampedExample {
    public static void main(String[] args) {
        // 初始化一个AtomicStampedReference，包含初始值和初始时间戳
        AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);

        // 获取当前值和版本戳
        String currentValue = ref.getReference();
        int currentStamp = ref.getStamp();

//        System.out.println("初始值: " + currentValue + ", 版本戳: " + currentStamp);

        // 使用 CAS 尝试更新值和版本戳
        boolean success = ref.compareAndSet("A", "B", currentStamp, currentStamp + 1); // 递增版本戳

        if (success) {
//            System.out.println("成功更新为 B");
        } else {
//            System.out.println("CAS 失败!");
        }

        // 将B 变回 A
        currentValue = ref.getReference();
        currentStamp = ref.getStamp();

        ref.compareAndSet("B", "A", currentStamp,currentStamp + 1);

        currentValue = ref.getReference();
        currentStamp = ref.getStamp(); // 此时版本戳已经改变

        // 再次尝试从 A 更新为 C，这时会失败
        success = ref.compareAndSet("A", "C", currentStamp, currentStamp + 1);

        if (success) {
//            System.out.println("成功更新为 C");
        } else {
//            System.out.println("CAS 失败 (ABA)"); // 会失败  因为版本戳已经变了
        }

//        System.out.println("最终值: " + ref.getReference() + ", 版本戳: " + ref.getStamp());
    }
}
